(function($){
    function puzzleImg(settings){
    	$.extend(this,settings);
    	return this.init(settings);
	}
    puzzleImg.prototype = {
        constructor : 'puzzleImg',
		init : function(settings){
        	var self = this;
            self.container = $(self.container);
        	self.settings = settings;
        	self.scale  = 1;
        	self.listStart = 0;
        	self.listLength = self.settings.imglist.imgSrc.length;
        	self.createPicList();
        	self.createTplList();
        	self.createCanvas();
		},
		//绑定图片处理事件
		bindEvent : function(){
			var self = this;
			// 左侧菜单可拖拽
			$('.puzzleImg-list-detail img').draggable({
				revert:true,
				proxy:'clone',
				onStartDrag:function(){
					$(this).draggable('options').cursor = 'not-allowed';
					$(this).draggable('proxy').css({
						'z-index':10,
						'width' : 200
					});
				},
				onStopDrag:function(){
					$(this).draggable('options').cursor='move';
				}
			});
			// 放置入画布
			$('div[name=puzzleImg-working] .working-col').droppable({
				onDragEnter:function(e,source){
					$(source).draggable('options').cursor='auto';
				},
				onDragLeave:function(e,source){
					$(source).draggable('options').cursor='not-allowed';
				},
				onDrop:function(e,source){
					var src = $(source).attr('src');
					var img = $('<img src='+src+'>');
					$(this).append(img);
					img.get(0).onload = function(){
						img.css({
			            	'width' : parseInt(img.width())/self.scale,
			            	'height': parseInt(img.height())/self.scale,
			            }).dragging({
			                move : 'both',
			                restricted : false,
			                changeSize : true,
			                supportDelete : true,
			                reIndex : true,
			                border: '1px solid #f5a351'
			            });
					}
				}
			});
		},
		//创建右侧图片列表
		createPicList : function(){
			var self = this;
			var $dom = self.container.find('div[name=puzzleImg-list]');
			var picList = '<div class="up disabled">▲</div><ul class="puzzleImg-list-detail">';
			$.each(self.settings.imglist.imgSrc,function(i,item){
                picList += '<li><img src="'+item+'" alt=""></li>';
			})
            picList +='</ul><div class="down">▼</div>';
            $dom.html(picList);
            $dom.css({
				'width' : self.settings.imglist.width,
				'height' : self.settings.imglist.height,
				'float' : 'right',
				'position':'relative'
			})
            $dom.find('.up,.down').css({
				'width' : self.settings.imglist.width
			})
			self.scrollPicList();
		},
		// 右侧图片点击滚动
		scrollPicList : function(){
			var self = this;
			var $dom = self.container.find('div[name=puzzleImg-list]'),$ul=$dom.find('ul');
			var $up = $dom.find('.up'),$down = $dom.find('.down');
			var oriTop = parseInt($ul.css('top'));
			var iLiHeight = parseInt($dom.find('li').height());
			var showNum = Math.ceil($dom.height()/iLiHeight);

			
			$up.off('click').on('click',function(){
				oriTop = parseInt($ul.css('top'))
				if(self.listStart-showNum >= 0){
					$ul.stop().animate({
						'top' : oriTop+iLiHeight*showNum + 'px'
					})
					$down.removeClass('disabled');
					self.listStart -= showNum;
				}else if (self.listStart-showNum < 0 && self.listStart>0){
					$ul.stop().animate({
						'top' : 0 + 'px'
					})
					self.listStart=0;
					$up.addClass('disabled');
				}
			})
			$down.off('click').on('click',function(){
				oriTop = parseInt($ul.css('top'));
				if(self.listStart + showNum <= self.listLength){
					$ul.stop().animate({
						'top' : oriTop-iLiHeight*showNum + 'px'
					})
					$up.removeClass('disabled');
					self.listStart += showNum;
				}else if(self.listStart + showNum > self.listLength && self.listStart < self.listLength){
					$ul.stop().animate({
						'top' : oriTop-iLiHeight*showNum + 'px'
					})
					$down.addClass('disabled');
					$up.removeClass('disabled');
					self.listStart = self.listLength;
				}
				
			})
			 
		},
		//创建画布
		createCanvas : function(){
			var self = this;
			var $dom = self.container.find('div[name=puzzleImg-working]');
			var $tplList = self.container.find('div[name=puzzleImg-tpl]');
			// 创建dom
			var cate = $tplList.find('li.active').data('val');
			var str = '';
			if(cate != 'custom'){
				var cNum = parseInt(cate.substring(3));
				for(var i=0;i<cNum;i++){
					str += '<div class="working-col"></div>';
				}
				$dom.html(str);
			}else{
				$dom.html('<div class="working-col" style="border:none;"></div>');
			}
			self.calcuCanvas();
		},
		// 计算等比例缩放的画布
    	calcuCanvas : function(){
    		var self = this;
			var $dom = self.container.find('div[name=puzzleImg-working]');
    		//计算列宽
			var $col = $dom.find('.working-col');
			var $space = $dom.find('.working-space');
			var wLt = false,hLt = false,finalCal='';

			$dom.css(self.settings.canvas.css);

			if(self.settings.canvas.width > self.settings.canvas.base.width){
				wLt = true;
			}else if (self.settings.canvas.height > self.settings.canvas.base.height){
				hLt = true;
			}

			if(wLt && !hLt){ //宽度大于基础宽度，以宽的比例缩放
				finalCal = 'width';
			}else if(!wLt && hLt){ //高度大于基础高度，以高的比例缩放
				finalCal = 'height';
			}else if (wLt && hLt){ //宽高均大于基础数值
				finalCal = self.settings.canvas.width/self.settings.canvas.base.width > self.settings.canvas.height/self.settings.canvas.base.height ? 'width' : 'height'
			}

			if(finalCal = 'width'){
				self.scale = self.settings.canvas.width/self.settings.canvas.base.width;
			}else if (finalCal = 'height'){
				self.scale = self.settings.canvas.height/self.settings.canvas.base.height;
			}

			var calcuHeight = self.settings.canvas.height / self.scale;
			var calcuWidth = self.settings.canvas.width / self.scale;

			$dom.css({
				'width' : calcuWidth,
				'height' : calcuHeight,
				'margin-top' : -calcuHeight/2 + 'px'
			})
			
			$col.css({
				width : Math.floor((calcuWidth-($col.length-1))/$col.length),
				height : calcuHeight
			});
			self.canvasAdjust();
			self.bindEvent();
		},
		//调整列宽
		canvasAdjust : function(){ 
			var self = this;
			var $area = self.container.find('div[name=puzzleImg-working]');
			var $cols = $area.find('.working-col');
			var oriWidth = [];
			var cursorJudge = [];
			var canAdjust = false,calculating = false,dire = 'right';
			var $target,$nextTarget;

			var storeWidth =  function(){
				oriWidth = [];
				cursorJudge = [];
				$cols.each(function(i,obj){
					oriWidth.push(parseInt($(obj).width()));
				})
				$.each(oriWidth,function(i,item){
					if(i == 0){
					  cursorJudge.push(item);
					}else if(i>0 && i != oriWidth.length-1){
					  cursorJudge.push(item + oriWidth[i-1])
					}
				})
			}
			storeWidth();
			$cols.mousemove(function(e){
				if(!calculating){
					var index = $(this).index();
					$target = $(this);
					if(index == 0){ // 第一个只能调整右边框
						if(e.pageX - $area.offset().left > cursorJudge[index]-10){
							canAdjust = true;
							dire = 'right';
						}else{
							canAdjust = false;
						}
					}else if(index == $cols.length-1){ // 最后一个只能调整左边框
						if(e.pageX - $area.offset().left < cursorJudge[index-1]+10){
							canAdjust = true;
							dire = 'left';
						}else{
							canAdjust = false;
						}
					}else{ // 其余左右均能调整
						if(e.pageX - $area.offset().left < cursorJudge[index]+10 && e.pageX - $area.offset().left > cursorJudge[index]-10){
							canAdjust = true;
							dire = 'right';
						}else if(e.pageX - $area.offset().left < cursorJudge[index-1]+10){
							canAdjust = true;
							dire = 'left';
						}else{
							canAdjust = false;
						}
					}
					if(canAdjust){
						$target.css({
							'cursor' : 'e-resize'
						})
					}else{
						$target.css({
							'cursor' : 'default'
						})
					}
				}
				
			})
			$cols.off('mousedown').on('mousedown',function(e){
				if(canAdjust && !calculating){
					calculating = true;
					var oriX = e.pageX;
					var tW = parseFloat($target.width()),nW='';
					if(dire == 'right'){
						$nextTarget = $target.next();
					}else{
						$nextTarget = $target.prev();
					}
					nW = parseFloat($nextTarget.width());
					$(document).off('mousemove').on('mousemove',function(e){
						var disX = e.pageX - oriX;
						if(dire == 'right'){
							if(tW+disX<=10 || nW-disX <=10){
								return;
							}
							$target.css({
								width : tW+disX
							})
							$nextTarget.css({
								width : nW-disX
							})
						}else{
							if(tW-disX<=10 || nW+disX <=10){
								return;
							}
							$target.css({
								width : tW-disX
							})
							$nextTarget.css({
								width : nW+disX
							})
						}

					})
				}
				$(document).off('mouseup').on('mouseup',function(){
					calculating = false;
					storeWidth();
					$(document).off('mousemove');
					$(document).off('mouseup');
				})
				
			})
			
		},
		// 创建右侧模板列表
		createTplList : function(){
			var self = this;
			var tpl = "<ul>"
			$dom = self.container.find('div[name=puzzleImg-tpl]');

			// 自定义模板
			if(self.settings.tplList.custom){
				tpl += '<li data-val="custom">'+
							'<img src="./images/tpl_01.jpg" alt="">'+
						'</li>'
			}
			// 两列模板
			if(self.settings.tplList.col2){
				tpl += '<li data-val="col2">'+
							'<img src="./images/tpl_01.jpg" alt="">'+
						'</li>'
			}
			// 三列模板
			if(self.settings.tplList.col3){
				tpl += '<li data-val="col3" class="active">'+
							'<img src="./images/tpl_01.jpg" alt="">'+
						'</li>'
			}

			tpl += '</ul>';
			$dom.html(tpl).css(self.settings.tplList.css);
			$dom.find('li').off('click').on('click',function(){
				$(this).siblings().removeClass('active').end().addClass('active');
				self.createCanvas();
			})
		},
		returnVal : function(){
			var self = this;
			// 返回比例，在保存图片的时候统一放大
			return self.scale;
		}
	}
	$.fn.puzzleImg = function(settings){
    	var lmObj;
    	var thisDom;
		// 合并配置
		$.extend(true,$.fn.puzzleImg.defaultSetting,settings);
		//通过迭代的方式找到当前的jq对象
		console.log($.fn.puzzleImg.defaultSetting)
		this.each(function(key,the){
            lmObj = new puzzleImg($.extend({container:the},$.fn.puzzleImg.defaultSetting))
		})

        return lmObj.returnVal();
	}

	$.fn.puzzleImg.defaultSetting = {
		imglist : {
			'width' : 140,
			'height' : 700,
			'imgSrc' : []
		},
		canvas : {
			'base' : {
				'width' : 600,
				'height' : 600
			},
			'width' : 600,// 画布宽度
			'height' : 600,// 画布高度
			'css' : { 
				'background':'#fff',
				'margin' : 'auto',
				'border' : '1px solid #000',
				'position': 'relative',
				'top' : '50%'
			}
		},
		tplList : {
			'col3' : true,
			'col2' : true,
            'custom' : true,
            'css' : {
            	'width':250,
    			'height':700,
    			'padding' : 10 
            }
		}
	}
})(jQuery);